package com.define.ssh.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.define.ssh.dao.FuncDao;
import com.define.ssh.model.Func;

@Repository("funcDaoImpl")
public class FuncDaoImpl extends BaseDaoImpl<Func, Long> implements FuncDao {
	/***
	 * 根据角色id获取功能列表
	 * 
	 * @param role_id
	 *            角色id
	 * @return
	 */
	@Override
	public List<Func> getFuncByRoleId(Long role_id) {
		String hql = "from Func f where 1=1 and f.isvalid=0 and f.levels!=0 ";
		hql += " and f.id in(select rf.func.id from RoleFunc rf where rf.role.id='"
				+ role_id + "') order by f.parentId,f.orderSn asc ";
		final List<Func> list = getSession().createQuery(hql).list();
		list.addAll(getfuncRoot(role_id));
		return list;
	}

	/***
	 * 获取权限所在的根节点
	 * 
	 * @param role_id
	 * @return
	 */
	@Override
	public List<Func> getfuncRoot(Long role_id) {
		String hql = " from Func t where t.isvalid=0 and t.parentId='0' and t.levels=0 and t.id in(select f.parentId from Func f where 1=1 and f.isvalid=0 ";
		hql += " and f.id in(select rf.func.id from RoleFunc rf where rf.role.id='"
				+ role_id
				+ "') and f.levels!=0  and f.parentId!='0'  group by f.parentId ) order by orderSn ";
		return getSession().createQuery(hql).list();
	}

	/***
	 * 根据用户id获取功能列表
	 * 
	 * @param user_id
	 *            角色id
	 * @return
	 */
	@Override
	public List<Func> getFuncByUserId(Long user_id) {
		String hql = "from Func f where 1=1 and f.isvalid=0 and f.levels!=0 ";
		hql += " and f.id in(select uf.func.id from UserFunc uf where uf.user.id='"
				+ user_id + "') order by f.parentId,f.orderSn asc ";
		final List<Func> list = getSession().createQuery(hql).list();
		list.addAll(getfuncRootByUserId(user_id));
		return list;
	}

	/***
	 * 根据用户id获取权限所在的根节点
	 * 
	 * @param user_id
	 * @return
	 */
	@Override
	public List<Func> getfuncRootByUserId(Long user_id) {
		String hql = " from Func t where t.isvalid=0 and t.parentId='0' and t.levels=0 and t.id in(select f.parentId from Func f where 1=1 and f.isvalid=0 ";
		hql += " and f.id in(select uf.func.id from UserFunc uf where uf.user.id='"
				+ user_id
				+ "') and f.levels!=0  and f.parentId!='0'  group by f.parentId ) order by orderSn ";
		return getSession().createQuery(hql).list();
	}
}
